﻿var columns = [];
layui.use(['table', 'form'], function () {
    let table = layui.table;
    let form = layui.form;
    let dropdown = layui.dropdown;
    form.render();

    // initDict();

    let tableId = $('#id').val();
    getObjData(table, tableId, form, dropdown);


    form.on('switch(isPkFilter)', function (obj) {
        columnFilter(this.value, obj.elem.checked, this.name);
    });
    form.on('switch(isUsableFilter)', function (obj) {
        columnFilter(this.value, obj.elem.checked, this.name);
    });
    form.on('switch(isUsableFilter)', function (obj) {
        columnFilter(this.value, obj.elem.checked, this.name);
    });
    form.on('switch(isDtoFilter)', function (obj) {
        columnFilter(this.value, obj.elem.checked, this.name);
    });
    form.on('switch(isVoFilter)', function (obj) {
        columnFilter(this.value, obj.elem.checked, this.name);
    });
    form.on('switch(isFormFilter)', function (obj) {
        columnFilter(this.value, obj.elem.checked, this.name);
    });
    form.on('switch(isRequiredFilter)', function (obj) {
        columnFilter(this.value, obj.elem.checked, this.name);
    });
    form.on('switch(isListFilter)', function (obj) {
        columnFilter(this.value, obj.elem.checked, this.name);
    });
    form.on('switch(isExpFilter)', function (obj) {
        columnFilter(this.value, obj.elem.checked, this.name);
    });
    form.on('switch(isQueryFilter)', function (obj) {
        columnFilter(this.value, obj.elem.checked, this.name);
    });

    // form.on('select', function (obj) {
    //     console.log('queryTypeFilter', obj)
    // })

    /* 提交 */
    form.on('submit(editTableInfo)', function (data) {
        let obj = data.field;
        assignmentField(obj);
        obj.columns = columns;
        $.form.submit({
            url: HTTP_BIZ_URI + '/dev/table/info/' + data.field.id, data: obj, callback: function (res) {
                parent.reloadTableData();
                $.msg.okMsg(res.msg);
            }
        })
    });

});

function getObjData(table, tableId, form, dropdown) {
    $.ajax({
        url: HTTP_BIZ_URI + '/dev/table/info/' + tableId, success: function (res) {
            if (200 === res.status) {
                initForm(res.data, form)
                columns = res.data.columns;
                table.render(tableOptions(table, columns, dropdown));

                form.render();
            } else {
                layer.alert('获取数据失败', {title: "系统提示", icon: 2});
            }
        }
    })
}

function initForm(data, form) {
    $("#tableName").val(data.tableName);
    $("#funcName").val(data.funcName);
    $("#funcAuthor").val(data.funcAuthor);
    $("#clazzName").val(data.clazzName);
    $("#menuId").val(data.menuId);
    $("#appId").val(data.appId);
    $("#contextPath").val(data.contextPath);

    $("#rearUri").val(data.rearUri);
    $("#rearPackage").val(data.rearPackage);
    $("#moduleName").val(data.moduleName);

    $("#frontPackage").val(data.frontPackage);
    $("#remarks").val(data.remarks);


    let tpl = ['biz', 'default'];
    let rearTemp = data.rearTemp;
    let html = '';
    for (let i = 0; i < tpl.length; i++) {
        html = '<input type="radio" name="rearTemp" value="' + tpl[i] + '" title="' + tpl[i] + '"';
        if (rearTemp === tpl[i]) {
            html += 'checked=""'
        }
        html += '>'
        $("#rearTempBlock").append(html)
    }


    initBuilderBlock('rearDddBlock', 'rearDdd', data.rearDdd);
    initBuilderBlock('buildEntityBlock', 'buildEntity', data.buildEntity);
    initBuilderBlock('buildQueryBlock', 'buildQuery', data.buildQuery);
    initBuilderBlock('buildDtoBlock', 'buildDto', data.buildDto);
    initBuilderBlock('buildVoBlock', 'buildVo', data.buildVo);
    initBuilderBlock('rearSplitBlock', 'rearSplit', data.rearSplit);
    initBuilderBlock('useLombokBlock', 'useLombok', data.useLombok);
    initBuilderBlock('useSwaggerBlock', 'useSwagger', data.useSwagger);


    selectUiStyle(data.frontUiStyle);
    browserOpeningIframe(data.iframe);


    form.render();
}


function initBuilderBlock(id, name, value) {
    if (null === value || undefined === value || '' === value) {
        value = '0';
    }
    let yesOrNo = ['1', '0'];
    let html = '';
    for (let i = 0; i < yesOrNo.length; i++) {
        html = '<input type="radio" id="' + name + '" name="' + name + '"  value="' + yesOrNo[i] + '" ';
        if ('1' === yesOrNo[i] || 1 === yesOrNo[i]) {
            html += ' title="是" ';
        } else {
            html += ' title="否" ';
        }
        if (value === yesOrNo[i]) {
            html += 'checked=""'
        }
        html += '>'
        $("#" + id).append(html)
    }
}

/**
 * 浏览器打开方式
 * @param iframe
 */
function browserOpeningIframe(iframe) {
    let iframeArr = [{
        value: '_iframe', label: '_iframe(内嵌)'
    }, {
        value: '_parent', label: '_parent(父窗口打开)'
    }, {
        value: '_blank', label: '_blank(新窗口打开)'
    }, {
        value: '_component', label: '_component(单页面)'
    }, {
        value: '_layer', label: '_layer(弹窗网页)'
    }];
    let html = '<option value="">请选择浏览器打开方式</option>';
    for (let i = 0; i < iframeArr.length; i++) {
        if (iframe === iframeArr[i].value) {
            html += '<option value="' + iframeArr[i].value + '"  selected>' + iframeArr[i].label + '</option>';
        } else {
            html += '<option value="' + iframeArr[i].value + '">' + iframeArr[i].label + '</option>';
        }
    }
    $("#iframe").append(html)
}

/**
 * UI 类型
 * @param iframe
 */
function selectUiStyle(uiStyle) {
    let uiStyleArr = [{
        value: 'LAY_UI', label: 'layUI (JQ)'
    }, {
        value: 'VUE_LAY_UI', label: 'LAY_UI(VUE3/TS)'
    }, {
        value: 'VUE_ELEMENT', label: 'ELEMENT_UI(VUE3/TS)'
    }];
    let html = '<option value="">请选择 UI 类型</option>';
    for (let i = 0; i < uiStyleArr.length; i++) {
        if (uiStyle === uiStyleArr[i].value) {
            html += '<option value="' + uiStyleArr[i].value + '"  selected>' + uiStyleArr[i].label + '</option>';
        } else {
            html += '<option value="' + uiStyleArr[i].value + '">' + uiStyleArr[i].label + '</option>';
        }
    }
    $("#frontUiStyle").append(html)
}


function tableOptions(table, data, dropdown) {
    return {
        id: 'layTableInfo',
        elem: '#layTable',
        cellMinWidth: 80,
        page: false,
        data: data,
        limit: 1000, // height: 'full-90',
        // height: '700px',
        maxHeight: '650px',
        cols: [[/* fixed: 'left', */
            {
                field: 'columnName',
                title: '表字段',
                align: "center",
                width: 150,
                templet: function (d) {
                    return d.columnName + '</br>(' + d.columnType + ')';
                }
            },
            {
                field: 'columnComment',
                title: '字段描述',
                align: "center",
                minWidth: 180,
                edit: 'text'
            },
            {
                field: 'javaField',
                title: 'JAVA类型',
                align: "center",
                minWidth: 180,
                edit: 'text'
            },
            // {
            //     field: 'javaType', title: '实体类字段', align: "center", width: 150, templet: function (d) {
            //         return selectHtmlTemplate(d.id, d.javaType, 'javaType')
            //     }
            // },

            {
                field: 'javaType',
                title: '实体类字段',
                width: 180,
                unresize: true,
                align: 'center',
                templet: '#TPL-dropdpwn-java-type'
            },

            {field: 'isPk', title: '主键', align: "center", templet: '#isPkTpl', width: 90}, {
                field: 'isUsable', title: '是否使用', align: "center", templet: '#isUsableTpl', width: 100
            }, {field: 'isDto', title: 'DTO 字段', align: "center", templet: '#isDtoTpl', width: 100}, {
                field: 'isVo', title: 'VO 字段', align: "center", templet: '#isVoTpl', width: 100
            }, {
                field: 'isForm', title: '表单字段', align: "center", templet: '#isFormTpl', width: 100
            }, {
                field: 'isRequired', title: '必填', align: "center", templet: '#isRequiredTpl', width: 100
            },

            {
                field: 'htmlType',
                title: '显示类型',
                width: 180,
                unresize: true,
                align: 'center',
                templet: '#TPL-dropdpwn-html-type'
            },
            {
                field: 'isList', title: '列表字段', align: "center", templet: '#isListTpl', width: 100
            }, {
                field: 'isExp', title: '导出字段', align: "center", templet: '#isExpTpl', width: 100
            }, {field: 'isQuery', title: '查询字段', align: "center", templet: '#isQueryTpl', width: 100},

            // {
            //     field: 'queryType', title: '查询方式', align: "center", width: 130, templet: function (d) {
            //         return selectHtmlTemplate(d.id, d.queryType, 'queryType')
            //     }
            // },


            {
                field: 'queryType',
                title: '查询方式',
                width: 180,
                unresize: true,
                align: 'center',
                templet: '#TPL-dropdpwn-query'
            },

            /*            {
                            field: 'htmlType', title: '显示类型', align: "center", width: 130, templet: function (d) {
                                return selectHtmlTemplate(d.id, d.htmlType, 'htmlType')
                            }
                        },*/




            // {
            //     field: 'dictType', title: '字典类型', align: "center", width: 130, templet: function (d) {
            //         return selectHtmlTemplate(d.id, d.dictType, 'dictType')
            //     }
            // },

            // {
            //     field: 'dictType',
            //     title: '字典类型',
            //     width: 180,
            //     unresize: true,
            //     align: 'center',
            //     templet: '#TPL-dropdpwn-dict-data'
            // },


            {field: 'sort', title: '排序', align: "center", edit: 'text', width: 60},]],
        done: function (res, curr, count) {
            let x = 10;
            let y = 20;
            let newTitle = '';
            $('td').each(function (index, element) {
                if ($(element).text() !== '' && $(element).text() != null) {
                    $(element).attr('title', $(element).text()).addClass('tdTitle');
                }
            });
            $(".layui-table-col-special").removeClass("tdTitle").attr("title", "");
            $('td.tdTitle').mouseover(function (e) {
                newTitle = this.title;
                this.title = '';
                $('body').append('<div id="tooltip">' + newTitle + '</div>');
                $('#tooltip').css({
                    'left': (e.pageX + x + 'px'), 'top': (e.pageY + y + 'px'),
                }).show();
            }).mouseout(function () {
                this.title = newTitle;
                $('#tooltip').remove();
            }).mousemove(function (e) {
                $('#tooltip').css({
                    'left': (e.pageX + x + 'px'), 'top': (e.pageY + y + 'px')
                }).show();
            })


            /**
             * 获取当前行数据(必须设置)
             */
            let options = this;
            table.getRowData = function (tableId, elem) {
                let index = $(elem).closest('tr').data('index');
                return table.cache[tableId][index] || {};
            };

            /** java 类型选择 */
            let javaTypeDate = javaType();
            let javaTypeArr = [];
            for (let i = 0; i < javaTypeDate.length; i++) {
                javaTypeArr.push({
                    id: javaTypeDate[i].value, title: javaTypeDate[i].value,
                })
            }
            dropdown.render({
                elem: '.dropdpwn-java-type', // trigger: 'hover',
                data: javaTypeArr, click: function (obj) {
                    let rowData = table.getRowData(options.id, this.elem); // 获取当前行数据(如 id 等字段，以作为数据修改的索引)
                    this.elem.find('span').html(obj.title);
                    // 更新数据中对应的字段
                    rowData.javaTypeTitle = obj.title;
                    for (let i = 0; i < columns.length; i++) {
                        if (columns[i].columnId !== rowData.columnId) {
                            continue;
                        }
                        console.log('dataId: ' + rowData.columnId + ', columnsId:  ' + columns[i].columnId)
                        columns[i].javaType = obj.id;
                        columns[i].javaTypeTitle = obj.title;
                        break;
                    }
                }
            });


            /** 查询方式 */
            let queryTypeDate = queryType();
            let queryTypeArr = [];
            for (let i = 0; i < queryTypeDate.length; i++) {
                queryTypeArr.push({
                    id: queryTypeDate[i].value, title: queryTypeDate[i].label,
                })
            }
            dropdown.render({
                elem: '.dropdpwn-query', // trigger: 'hover',
                data: queryTypeArr, click: function (obj) {
                    let rowData = table.getRowData(options.id, this.elem); // 获取当前行数据(如 id 等字段，以作为数据修改的索引)
                    this.elem.find('span').html(obj.title);
                    // 更新数据中对应的字段
                    rowData.queryType = obj.title;
                    for (let i = 0; i < columns.length; i++) {
                        if (columns[i].columnId !== rowData.columnId) {
                            continue;
                        }
                        columns[i].queryType = obj.id;
                        columns[i].queryTitle = obj.title;
                        break;
                    }
                }
            });

            /** html 显示方式 */
            let htmlTypeDate = htmlType();
            let htmlTypeArr = [];
            for (let i = 0; i < htmlTypeDate.length; i++) {
                htmlTypeArr.push({
                    id: htmlTypeDate[i].value, title: htmlTypeDate[i].label,
                });
            }
            dropdown.render({
                elem: '.dropdpwn-html-type', //  trigger: 'hover',
                data: htmlTypeArr, click: function (obj) {
                    let rowData = table.getRowData(options.id, this.elem); // 获取当前行数据(如 id 等字段，以作为数据修改的索引)
                    this.elem.find('span').html(obj.title);
                    // 更新数据中对应的字段
                    rowData.htmlType = obj.title;
                    for (let i = 0; i < columns.length; i++) {
                        if (columns[i].columnId !== rowData.columnId) {
                            continue;
                        }
                        columns[i].htmlType = obj.id;
                        columns[i].htmlTitle = obj.title;
                        break;
                    }
                }
            });


            /** 数据字典 */
            let dictTypeDate = dictList;
            let dictTypeArr = [];
            for (let i = 0; i < dictTypeDate.length; i++) {
                dictTypeArr.push({
                    id: dictTypeDate[i].value, title: dictTypeDate[i].label,
                });
            }
            dropdown.render({
                elem: '.dropdpwn-dict-data', //  trigger: 'hover',
                data: dictTypeArr, click: function (obj) {
                    let data = table.getRowData(options.id, this.elem); // 获取当前行数据(如 id 等字段，以作为数据修改的索引)
                    this.elem.find('span').html(obj.title);
                    // 更新数据中对应的字段
                    data.dictType = obj.title;
                    for (let i = 0; i < columns.length; i++) {
                        if (columns[i].columnId !== data.columnId) {
                            continue;
                        }
                        columns[i].dictType = obj.id;
                        columns[i].dictTitle = obj.title;
                        break;
                    }
                }
            });


        },


    }
}
